import { isDate } from './type'

interface formateTimeType {
    YYYY?: string | number
    MM?: string | number
    DD?: string | number
    hh?: string | number
    mm?: string | number
    ss?: string | number
}

export const formatDate = (dateTime: string | Date | number | formateTimeType, format: string) => {
    if (!dateTime) {
        return ''
    }
    try {
        if (typeof dateTime === 'string' || typeof dateTime === 'number' || isDate(dateTime)) {
            const time = new Date(dateTime)
            const config: Record<string, string | number> = {
                'Y+': time.getFullYear(),
                'M+': time.getMonth() + 1, //月份
                'D+': time.getDate(), //日
                'h+': time.getHours(), //小时
                'H+': time.getHours() % 12 == 0 ? 12 : time.getHours() % 12, //小时
                'm+': time.getMinutes(), //分
                's+': time.getSeconds() //秒
            }
            let newFormat = format
            for (const k in config) {
                const ret = new RegExp('(' + k + ')').exec(format)
                if (ret) {
                    const value = config[k].toString()
                    newFormat = newFormat.replace(
                        ret[1],
                        ret[0].length === 1 ? value : value.padStart(ret[1].length, '0')
                    )
                }
            }
            return newFormat
        }
        return ''
    } catch (error) {
        return ''
    }
}
